import React, { useEffect, useState } from 'react';
import { PluginProps } from 'react-markdown-editor-lite';
import { Modal, Form, Input, Checkbox } from 'antd';

function Counter(props: PluginProps) {
    const { editor, config } = props;
    const [open, setOpen] = useState(false);
    const [form] = Form.useForm();

    useEffect(() => {
        if (config) {
            const { url, pic, danmu, autoplay } = config;
            form.setFieldsValue({
                url,
                pic,
                danmu,
                autoplay,
            });
        }
    }, [config, form]);

    const handleClick = () => {
        setOpen(true);
    };

    const handleOk = async () => {
        const values = await form.validateFields();
        const { url, pic, danmu, autoplay } = values;

        let tag = '[dplayer url="' + url + '" pic="' + pic + '" ';
        if (!danmu) tag += 'danmu="' + danmu + '" ';
        if (autoplay) tag += 'autoplay="' + autoplay + '" ';
        tag += '/]\n';
        editor.insertText(tag);
        setOpen(false);
    };

    const handleCancel = () => {
        setOpen(false);
    };

    return (
        <>
            <span title='插入视频' className='button button-type-counter' onClick={handleClick}>
                <img
                    alt='插入视频'
                    src=''
                />
            </span>
            <Modal open={open} title='插入视频' onOk={handleOk} onCancel={handleCancel}>
                <Form form={form}>
                    <Form.Item label='链接' name='url'>
                        <Input placeholder='链接' />
                    </Form.Item>
                    <Form.Item label='封面图' name='pic'>
                        <Input placeholder='封面图' />
                    </Form.Item>
                    <Form.Item label='开启弹幕' name='danmu'>
                        <Checkbox />
                    </Form.Item>
                    <Form.Item label='自动播放' name='autoplay'>
                        <Checkbox />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
}
// Define default config if required
Counter.defaultConfig = {
    url: '',
    pic: '',
    danmu: '',
    autoplay: false,
};
Counter.align = 'left';
Counter.pluginName = 'counter';

export default Counter;
